package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.soledroid.Model.Dish;

import android.app.*;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class OfferActivity extends Activity{

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.offer);

		final ArrayList<Dish> dishes = this.fetchDishes();

		ListView lv = (ListView) findViewById(R.id.offerListView);
		lv.setAdapter(new ArrayAdapter<Dish>(this, R.layout.list_item, dishes));
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent();
				i.setClass(OfferActivity.this, DishActivity.class);

				Dish dish = dishes.get(position);
				i.putExtra("name", dish.getName());
				i.putExtra("id", dish.getId());

				startActivity(i);
			}
		});
	}

	public ArrayList<Dish> fetchDishes()
	{
		ArrayList<Dish> listItems = new ArrayList<Dish>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/offer");
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);

					Dish dish = new Dish(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
							jo.getString("description"), jo.getString("price"), jo.getInt("stall_id"),
							jo.getInt("on_promotion") == 1, jo.getDouble("rating"));
					listItems.add(dish);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 

		return listItems;
	}
}
